﻿namespace ImageWallControl.BrushProviders
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Xml.Linq;
    using Random = ImageWallControl.Random;

    public class FlickrBrushProvider : IBrushProvider
    {
        private const string ApiKey = "<<your api key>>";
        private const string Secret = "<<your secret>>";

        private const string InterestingUrl =
            "http://api.flickr.com/services/rest/?method=flickr.interestingness.getList&api_key={1}";

        private const string SearchUrl =
            "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key={1}&text={0}";

        private Action<IEnumerable<Brush>> _afterInitialize;

        protected IEnumerable<FlickrPhoto> Photos { get; set; }
        protected IEnumerable<ImageBrush> Images { get; set; }

        public void Initialize(Action<IEnumerable<Brush>> afterInitialize)
        {
            _afterInitialize = afterInitialize;
            var topic = "cats";
            var url = String.Format(InterestingUrl, topic, ApiKey, Secret);

            var flickRService = new WebClient();
            flickRService.DownloadStringCompleted += DownloadStringCompleted;
            flickRService.DownloadStringAsync(new Uri(url));
        }

        public Brush GetBrush()
        {
            return Images.OrderBy(x => Random.Generator.Next(99)).First();
        }

        private void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            var xmlPhotos = XDocument.Parse(e.Result);
            if (e.Error != null ||
                xmlPhotos.Element("rsp").Attribute("stat").Value == "fail")
            {
                string results = e.Result;
                throw new Exception(results);
            }

            Photos = from photo in xmlPhotos.Element("rsp").Element("photos").Descendants().ToList()
                     select new FlickrPhoto
                                {
                                    Id = (string) photo.Attribute("id"),
                                    Owner = (string) photo.Attribute("owner"),
                                    Secret = (string) photo.Attribute("secret"),
                                    Server = (string) photo.Attribute("server"),
                                    Farm = (string) photo.Attribute("farm"),
                                    Title = (string) photo.Attribute("title"),
                                };

            Images = from photo in Photos.OrderBy(x => Random.Generator.Next(99))
                     select
                         new ImageBrush
                             {
                                 ImageSource = new BitmapImage
                                                   {
                                                       UriSource = new Uri(photo.ImageUrl),
                                                       CreateOptions = BitmapCreateOptions.None
                                                   }
                             };

            _afterInitialize(Images.Cast<Brush>());
        }
    }

    public class FlickrPhoto
    {
        public string Id { get; set; }
        public string Owner { get; set; }
        public string Secret { get; set; }
        public string Server { get; set; }
        public string Farm { get; set; }
        public string Title { get; set; }

        public string ImageUrl
        {
            get
            {
                return string.Format("http://farm{0}.static.flickr.com/{1}/{2}_{3}.jpg",
                                     Farm, Server, Id, Secret);
            }
        }
    }
}